<script setup>
import { ref, onMounted, nextTick } from 'vue'
import axios from '../utils/axios'
import { ElMessage } from 'element-plus'

const question = ref('')
const loading = ref(false)
const chatHistory = ref([])
const historyLoading = ref(false)
const chatHistoryRef = ref(null)
const selectedModel = ref('qwen')

// 获取最近10条历史记录
const fetchHistory = async () => {
  historyLoading.value = true
  try {
    const response = await axios.get('/questions', {
      params: {
        page: 0,
        size: 10
      }
    })
    // 反转数组顺序，使最早的记录在上面
    chatHistory.value = response.data.content
      .map(item => ({
        id: item.id,
        question: item.content,
        answer: item.answer || '等待AI回答...',
        timestamp: new Date(item.createdAt).toLocaleString(),
        username: item.username,
        updatedAt: item.updatedAt ? new Date(item.updatedAt).toLocaleString() : null
      }))
      .reverse() // 反转数组顺序
    
    // 滚动到底部
    await scrollToBottom()
  } catch (error) {
    console.error('Error fetching history:', error)
    ElMessage.error('获取历史记录失败：' + (error.response?.data?.message || '未知错误'))
  } finally {
    historyLoading.value = false
  }
}

const scrollToBottom = async () => {
  await nextTick()
  if (chatHistoryRef.value) {
    chatHistoryRef.value.scrollTop = chatHistoryRef.value.scrollHeight
  }
}

const sendQuestion = async () => {
  if (!question.value.trim()) {
    ElMessage.warning('请输入问题')
    return
  }

  loading.value = true
  try {
    const response = await axios.post('/questions', {
      content: question.value,
      inputType: 'TEXT',
      model: selectedModel.value
    })

    // 将新的问答添加到历史记录的末尾
    chatHistory.value.push({
      id: response.data.id,
      question: question.value,
      answer: response.data.answer,
      timestamp: new Date().toLocaleString(),
      username: response.data.username
    })

    // 保持只显示最近10条记录
    if (chatHistory.value.length > 10) {
      chatHistory.value = chatHistory.value.slice(-10)
    }

    question.value = ''
    // 滚动到底部显示最新消息
    await scrollToBottom()
  } catch (error) {
    console.error('Error sending question:', error)
    ElMessage.error('提问失败：' + (error.response?.data?.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

const addToWrongQuestions = async (item) => {
  try {
    const wrongQuestionRequest = {
      questionId: item.id,
      userAnswer: item.question,
      correctAnswer: item.answer,
      analysis: ''
    }
    
    await axios.post('/wrong-questions', wrongQuestionRequest)
    ElMessage.success('已添加到备忘录')
  } catch (error) {
    console.error('Error adding to wrong questions:', error)
  }
}

onMounted(() => {
  fetchHistory()
})
</script>

<template>
  <div class="qa-container">
    <div 
      ref="chatHistoryRef"
      class="chat-history" 
      v-loading="historyLoading"
    >
      <el-empty v-if="chatHistory.length === 0" description="暂无问答记录" />
      <template v-else>
        <el-card v-for="(item, index) in chatHistory" :key="index" class="qa-item">
          <div class="question">
            <strong>问题：</strong>{{ item.question }}
          </div>
          <div class="answer" :class="{ 'pending': !item.answer }">
            <strong>答案：</strong>{{ item.answer }}
          </div>
          <div class="actions">
            <el-button 
              type="primary" 
              size="small" 
              @click="addToWrongQuestions(item)"
              :disabled="!item.answer"
            >
              添加到备忘录
            </el-button>
          </div>
          <div class="meta-info">
            <span class="username" v-if="item.username">提问者：{{ item.username }}</span>
            <span class="timestamp">提问时间：{{ item.timestamp }}</span>
            <span class="timestamp" v-if="item.updatedAt">更新时间：{{ item.updatedAt }}</span>
          </div>
        </el-card>
      </template>
    </div>
    
    <div class="input-wrapper">
      <div class="model-select">
        <el-select v-model="selectedModel" placeholder="选择AI模型" style="width: 150px">
          <el-option label="通义千问" value="qwen" />
          <el-option label="Deepseek" value="deepseek" />
        </el-select>
      </div>
      <el-input
        v-model="question"
        type="textarea"
        :rows="4"
        placeholder="请输入您的问题..."
        :disabled="loading"
        @keyup.enter.ctrl="sendQuestion"
      />
      <div class="button-group">
        <el-button
          type="primary"
          :loading="loading"
          @click="sendQuestion"
          style="margin-top: 10px; width: 100%"
        >
          发送问题
        </el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.qa-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 120px);
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 20px;
  scroll-behavior: smooth; /* 添加平滑滚动效果 */
}

.qa-item {
  margin-bottom: 15px;
}

.question, .answer {
  margin-bottom: 10px;
  white-space: pre-wrap;
  word-break: break-all;
}

.actions {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

.meta-info {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
  display: flex;
  gap: 15px;
}

.username {
  color: #409EFF;
}

.input-wrapper {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.model-select {
  display: flex;
  justify-content: flex-end;
}

.button-group {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__body) {
  padding: 15px;
}

.pending {
  color: #909399;
  font-style: italic;
}
</style> 